//Players can not move while they are parented
function PlayerMove( ply )
	if tonumber( ply:GetNWInt( "Parent" ) ) ~= 0 then
		ply:SetMoveType( MOVETYPE_NONE )
		return true
	end
end
hook.Add( "Move", "PlayerMove", PlayerMove )

if SERVER then
	//Update positions of child entities
	function UpdatePositions()
		//First update the childs of props (players)
		for _, pl in pairs(player.GetAll()) do
			if ents.GetByIndex(pl:GetNWInt( "Parent" )) ~= NULL then
				local Offset = pl:GetNetworkedVector( "Offset" )
				local PropPos = ents.GetByIndex(pl:GetNWInt( "Parent" )):GetPos()
				pl:SetPos( PropPos - Offset )
			elseif pl:GetNWInt( "Parent" ) ~= 0 then
				pl:SetNWInt( "Parent", 0 )
				pl:SetMoveType( MOVETYPE_WALK )
			end
		end
		
		for _, ent in pairs(ents.GetAll()) do
			if !ent:IsPlayer() then
				if ents.GetByIndex(ent:GetNWInt( "Parent" )) ~= NULL then
					local Offset = ent:GetNetworkedVector( "Offset" )
					local PlyPos = ents.GetByIndex(ent:GetNWInt( "Parent" )):GetPos()
					ent:SetPos( PlyPos + Offset )
					ent:SetAngles( ent:GetNetworkedVector( "Rotation" ) )
				elseif ent:GetNWInt( "Parent" ) ~= 0 then
					ent:SetNWInt( "Parent", 0 )
				end
			end
		end
	end
	hook.Add( "Think", "UpdatePositions", UpdatePositions )

	function PlayerDeath( Ply )
		//Unweld when the parent stops existing, in this case the player
		Ply:SetNWInt( "Parent", 0 )
		Ply:SetMoveType( MOVETYPE_WALK )
		
		//Unweld entities weld to the player
		for _, ent in pairs(ents.GetAll()) do
			if ent:GetNWInt("Parent") == Ply:EntIndex() then
				ent:SetNWInt( "Parent", 0 )
				ent:SetParent( nil )
			end
		end
	end
	hook.Add( "PlayerDeath", "PlayerDeath", PlayerDeath )
	
	function EnterVehicle( Ply )
		if Ply:GetNWInt( "Parent" ) ~= 0 then
			return false
		end
	end
	hook.Add( "CanPlayerEnterVehicle", "EnterVehicle", EnterVehicle )
end